import pinyin from 'pinyin'   //拿到中文拼音首字母小写

export default {
    dir: '/BackEndAjax',
    url: 'yunguapp.cn',
    http: 'http://yunguapp.cn',                             //php站点
    color: "#A87CFF",                                       //后台主题颜色
    mp4List: ["video/mp4", "video/wmv"],                    //允许的视频格式
    imgType:['image/jpg', 'image/jpeg', 'image/png'],       //允许的图片格式
    health:'healthCertificate',                             //健康证目录
    life:'lifePhotos',                                      //生活照的目录
    treeData: [                         //鉴权管理目录

        {
            key: 'home',
            title: '首页',
            children: [
                {
                    key: 'statistics',
                    title: '信息统计',
                },
                {
                    key: 'pending',
                    title: "待处理事件"
                }
            ]
        },
        {
            key: 'managment',
            title: "管理",
            children: [
                {
                    key: 'product',
                    title: "产品管理",
                },
                {
                    key: 'technician',
                    title: "技师管理",
                },
                {
                    key: 'users',
                    title: "用户管理",
                },
                {
                    key: 'orders',
                    title: "订单管理",
                },
                {
                    key: 'superior',
                    title: "代理管理",
                },
            ]
        },
        {
            key: "traveling",
            title: "交通出行"
        },
        {
            key: 'coupon',
            title: "优惠卷活动",
        },

        {
            key: 'setting',
            title: "系统设置",
            children: [
                {
                    key: 'pay',
                    title: "支付设置"
                },
                {
                    key: 'homeBanner',
                    title: "首页广告设置"
                },
                {
                    key: 'foundaction',
                    title: "基础设置"
                },
                {
                    key: "payRule",
                    title: "退款规则设置"
                }
            ]
        },
        {
            key: "setUser",
            title: "角色设置",
        },
        {
            key: 'feedBack',
            title: '意见反馈',
        },
        {
            key: 'report',
            title: "举报投诉",
        },
        {
            key: 'service',
            title: '客服服务',
        },
    ],
    uuidADD() {                         //创建uuid
        const len = 32;      //32长度
        let radix = 16;    //16进制
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        let uuid = [], i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) {
                uuid[i] = chars[0 | Math.random() * radix];
            }
        } else {
            let r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    },
    branbData: (data) => {                 //面包屑函数
        let arry = [];  //保存空数组
        data.forEach((item, index) => {  //进行路由match数据的遍历
            let obj = {
                path: item.path.split('/').at(-1),  //只留路径的最后位置
                breadcrumbName: item.meta,
            }
            if (item.children && item.children.length > 0) {    //如果存在子路由
                let dataFilter = item.children.filter(res => {    //过滤出不和面包屑相冲突在路由
                    if (res.meta != data[index + 1].meta) {
                        return res
                    }
                })

                obj.children = dataFilter.map(da => {
                    return {
                        path: da.path,
                        breadcrumbName: da.meta
                    }
                })

            }
            arry.push(obj)
        });
        return arry
    },
    getLetters(numberString) {                  //数字转化为字母   例子:"00505"=>"ABD"
        const letters = ['A', 'B', 'C', 'D', 'E'];
        let result = '';

        for (let i = 0; i < numberString.length; i++) {
            if (numberString[i] === '0') {
                result += letters[i];
            } else if (numberString[i] !== '5') {
                result += '';
            }
        }

        return result;
    },
    convertToPinyin(str) {                       // 转换为拼音函数
        // 将字符串拆分为数组
        const chars = str.split('');

        // 遍历数组，获取每个字符的首字母拼音
        const result = chars.map((char) => {
            // 判断字符是否是中文
            if (/[\u4e00-\u9fa5]/.test(char)) {
                // 使用 pinyin 库转换字符为拼音
                const pinyinList = pinyin(char, {
                    style: pinyin.STYLE_FIRST_LETTER,
                });

                // 取首字母拼音
                const firstLetter = pinyinList[0][0];

                return firstLetter;
            } else {
                // 对非中文字符直接返回
                return char;
            }
        });

        // 返回拼音字符串
        return result.join('');
    },
    containsSpecialCharacters(str) {  //判断是否有非法字符
        var regex = /[!@#$%^&*()\[\]{}\|;:"<>`~\-_=+]/;
        return regex.test(str);
    },
    calculateRemainingDays(dateField) {         //转时间为多少天
        const targetDate = new Date(dateField);
        const currentTime = new Date();

        if (targetDate < currentTime) {
            return false;
        }

        const timeDiff = targetDate.getTime() - currentTime.getTime();
        const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // 计算剩余天数

        return daysRemaining;
    },
    compareObjects(obj1, obj2) {                //判断对象是否全部相等
        // 获取对象的所有属性名
        const keys1 = Object.keys(obj1);
        const keys2 = Object.keys(obj2);

        // 验证属性数量是否相等
        if (keys1.length !== keys2.length) {
            return false;
        }

        // 遍历对象的属性
        for (let key of keys1) {
            // 判断属性是否存在于两个对象中
            if (!obj2.hasOwnProperty(key)) {
                return false;
            }

            const value1 = obj1[key];
            const value2 = obj2[key];

            // 如果属性值是对象，则递归比较
            if (typeof value1 === 'object' && typeof value2 === 'object') {
                if (!compareObjects(value1, value2)) {
                    return false;
                }
            } else {
                // 比较属性值
                if (value1 !== value2) {
                    return false;
                }
            }
        }

        return true;
    },
    filterArray(A, B) {                             //鉴权管理转化数据
        // 创建一个空数组用于存储满足条件的元素
        const C = [];

        for (const obj of A) {
            // 如果当前对象的 key 值存在于 B 数组中，则添加整个对象到结果数组 C
            if (B.includes(obj.key)) {
                C.push(obj);
            }
            // 如果当前对象包含 children 属性且该属性是一个数组
            else if (obj.children && Array.isArray(obj.children)) {
                // 通过递归调用 filterArray() 函数过滤子元素
                const filteredChildren = this.filterArray(obj.children, B);

                // 如果经过过滤后的子元素数组不为空，则添加父元素和满足条件的子元素到结果数组 C
                if (filteredChildren.length > 0) {
                    C.push({
                        ...obj,
                        children: filteredChildren,
                    });
                }
            }
        }
        return C;
    },
    formatDateRange(dateRange) {                    //将日期进行转化 例子:20070614-20170614  返回['2007-06-14','2017-06-14']
        const startYear = dateRange.slice(0, 4);
        const startMonth = dateRange.slice(4, 6);
        const startDay = dateRange.slice(6, 8);

        const endYear = dateRange.slice(9, 13);
        const endMonth = dateRange.slice(13, 15);
        const endDay = dateRange.slice(15, 17);

        const startDate = `${startYear}-${startMonth}-${startDay}`;
        const endDate = `${endYear}-${endMonth}-${endDay}`;

        return [startDate, endDate];
    },
    generateNewArray(prototype, data) {       //鉴权数据转化成新数组
        const newArray = [];
        if (!Array.isArray(data)) return [];
        prototype.forEach((protoItem) => {
            const matchedParent = data.find((dataItem) => dataItem.key === protoItem.key);

            if (!protoItem.children) {
                if (matchedParent && matchedParent.key) {
                    newArray.push(protoItem.key);
                }
            } else {
                const prototypeChildrenCount = protoItem.children.length;
                const dataChildren = matchedParent ? matchedParent.children : [];

                if (dataChildren.length === prototypeChildrenCount) {
                    newArray.push(protoItem.key);
                }

                protoItem.children.forEach((child) => {
                    if (child.key && dataChildren.some((dataChild) => dataChild && dataChild.key === child.key)) {
                        newArray.push(child.key);
                    }
                });
            }
        });

        return newArray;
    },
    getBread(data, key) {                   //组件面包屑数据转化
        let datas = JSON.parse(JSON.stringify(data));
        let pObjs = {};
        let objs = {};

        datas.forEach(item => {
            if (item.key === key) {
                if (item.children && item.children.length > 0) {
                    objs = item.children[0];
                    pObjs = item;
                    pObjs.children = pObjs.children.filter(c => c !== objs);
                } else {
                    pObjs = item;
                }
            } else {

                if (item.children && item.children.length > 0) {
                    item.children.forEach(res => {

                        if (res.key == key) {

                            objs = res;
                            pObjs = item;
                            pObjs.children = pObjs.children.filter(c => c !== res);
                        }
                    });
                }
            }
        });


        const result = [
            {
                key: 'admin',
                title: '后台管理',
                children: data.filter(item => item.key !== pObjs.key)
            },
            pObjs
        ];

        if (Object.keys(objs).length > 0) {
            result.push(objs);
        }

        const ary = result.map(item => {
            item.path = item.key;

            if (item.children && item.children.length > 0) {

                item.children = item.children.map(res => {
                    res.path = res.key
                    return res;
                })

            }
            return item;
        })

        return ary;
    },
    validate: (rule, value) => {    //验证是否存在特殊字符|
        if (value.includes("|")) {
            return Promise.reject('含有特殊字符|');
        } else {
            return Promise.resolve()
        }
    },
    clockArray: (clockData) => {           //将加钟信息转换为新数组
        let fen_arry = [];
        if (!clockData) return null;         //但通过传入的是null或者undefined
        clockData.forEach(item => {
            let obj = fen_arry.find(i => i.orderg_clock_uid == item.orderg_clock_uid);  //undefined  || obj
            if (obj) {  //如果存在相同的订单号
                obj.children.push(item);
            } else {      //如果没有相同单号
                obj = {
                    orderg_clock_uid: item.orderg_clock_uid,     //加钟单号
                    time: item.calm_time,                        //下单时间
                    clock_amount: item.zong_amount,                   //总金额
                    clock_state: item.clock_state,               //是否支付
                    clock_project_time: item.clock_duration,         //总时长
                    key: item.orderg_clock_uid,
                    children: [item]                             //项目内容
                }
                fen_arry.push(obj)
            }
        })
        let weiData = fen_arry.find(i => i.clock_state == 0);  //找出未支付数据
        fen_arry = fen_arry.filter(i => i != weiData);                       //已支付数据
        fen_arry = fen_arry.sort((a, b) => {                            //进行排序
            const timeA = new Date(a.calm_time);
            const timeB = new Date(b.calm_time);
            return timeA - timeB;
        });
        fen_arry.forEach((i, index) => {                           //归类为第几次加钟
            i.clock_project_name = `第${index + 1}次加钟`
        })
        if (weiData) {
            weiData && (weiData.clock_project_name = '未支付加钟');                            //未支付为未加钟
            fen_arry.push(weiData);                                 //将未支付放在最后
        }

        return fen_arry;
    },
    calculateRemainingSeconds(start_time, duration, add_clock) {  //计算技师服务的结束时间
        // 将开始时间转换为 Date 对象
        if (!start_time) return 0;
        var start = new Date(start_time.replace(/-/g, "/"));

        // 获取当前时间的时间戳（毫秒）
        var currentTime = Date.now();

        // 计算开始时间的时间戳（毫秒）
        var startTimeStamp = start.getTime();

        // 计算剩余时间的时间戳差值（毫秒）
        var remainingTime = startTimeStamp + (duration * 60 * 1000) + (add_clock * 60 * 1000) - currentTime;

        // 将剩余时间的毫秒数转换为秒数
        var remainingSeconds = Math.round(remainingTime / 1000);

        return remainingSeconds;
    },
    generateCoverImage(file) {                      //  取出视频第一帧作为封面图像
        return new Promise((resolve, reject) => {
            const video = document.createElement('video');
            console.log(file);
            video.src = URL.createObjectURL(file)

            video.addEventListener('loadedmetadata', () => {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                video.play();
                setTimeout(() => {
                    video.pause();
                    context.drawImage(video, 0, 0);
                    canvas.toBlob((blob) => {
                        // 创建一个新的 File 对象，类型为 image/png
                        const coverImageFile = new File([blob], `${file.name.substring(0, file.name.lastIndexOf('.'))}.png`, { type: 'image/png' });
                        console.log(URL.createObjectURL(coverImageFile));
                        resolve(coverImageFile);
                    }, 'image/png');
                }, 500); // 延迟时间，以便视频开始播放
            });
            video.addEventListener('error', (err) => {
                console.log(err);
                console.log(err.target.error);
                console.log(err.target.error.message);
                reject(err);
            });
        });
    },
    getOrderState(state) {           //返回订单状态
        let num = state - 0;        //获取订单数字
        let obj = {
            0: "待支付",
            1: "待接单",
            2: "已接单",
            3: "已出发",
            4: "达到目的地",
            5: "开始服务",
            6: "服务完成",
            50: '服务加钟',
            90: "取消订单",
            91: "未接单退款",
            92: "已接单退款",
            93: "已出发退款",
            94: "已到达退款",
            100: "订单超时"
        }
        return obj[num];
    },
    getPayWay(state) {       //返回支付方式和颜色
        let obj = {
            alipay: '支付宝',
            wxpay: "微信",
            balance: "余额"
        }
        let color = {
            alipay: "skyblue",
            wxpay: "green",
            balance: "gray"
        }
        return [obj[state], color[state]];
    },
    getExamineState(state) {     //获取审核状态
        let obj = {
            0: '待审核',
            1: "审核通过",
            2: "审核不通过",

        }
        let color = {
            0: "red",
            1: "green",
            2: "red"
        }
        return [obj[state], color[state]];
    },
    getTechStatus(state){        //返回技师目前的状态
        let obj = {
            0: '初级考核',
            1: "待审核",
            2: "审核不通过",
            3:'上岗',
            4:"离职"
        }
        let color = {
            0: "#00FFFF",
            1: "gray",
            2: "red",
            3:"#008000",
            4:'red'
        }
        return [obj[state], color[state]];

    }

}


